﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace DDD4Fun.Common
{
    public class CDelegate
    {
        public static void TestDelegate()
        {
            Func<int, int, int> add = delegate(int i, int j)
            {
                return i + j;
            };

            Predicate<int> IfEqualFive = delegate(int i)
            {
                return i == 5;
            };

            Action<string> print = delegate(string msg)
            {
                if (IfEqualFive(Convert.ToInt32(msg)))
                {
                    Console.WriteLine(msg);
                }
            };

            //与上等价
            Func<int, int, int> add2 = (i, j) =>
            {
                return i + j;
            };

            Predicate<int> IfEqualFive2 = (i) =>
            {
                return i == 5;
            };

            Action<string> print2 = (msg)  =>
            {
                if (IfEqualFive(Convert.ToInt32(msg)))
                {
                    Console.WriteLine(msg);
                }
            };

            print(add(1, 4).ToString());
        }
    }

    class FileUploadedEventArgs : EventArgs
    {
        public int FileProgress { get; set; }
    }
    class FileUploader
    {
        //public delegate void FileUploadedHandler(int progress);
        //public  event FileUploadedHandler FileUploaded;
        public event EventHandler<FileUploadedEventArgs> FileUploaded;

        public void Upload()
        {
            int fileProgress = 100;
            FileUploadedEventArgs e = new FileUploadedEventArgs() { FileProgress = fileProgress };
            while (e.FileProgress > 0)
            {

                e.FileProgress--;
                if (FileUploaded != null)
                    FileUploaded(this,e);
            }
        }
        
    }
    class FileUploaderProgram
    {
        static void Progress(int progress)
        {
            Console.WriteLine(progress);
        }

        static void Progress2(int progress)
        {
            Console.WriteLine(string.Format("2{0}", progress));
        }

        static void dMain(string[] args)
        {

            //FileUploader fl = new FileUploader();
            ////fl.FileUploaded = Progress;
            //fl.FileUploaded += Progress2;

            ////fl fl.FileUploaded可被其他线程访问
            //Action ddd = () =>
            //{
            //    //fl.FileUploaded = Progress2;
            //};
            //Thread t = new Thread(new ThreadStart(ddd));
            //t.Start();

            //fl.Upload();

            FileUploader fl = new FileUploader();
            fl.FileUploaded += (o, e) => { };
            fl.Upload();
        }
    }
}
